from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
from django.views import View
from users.models import Address
from django_redis import get_redis_connection
from goods.models import  SKU
from decimal import Decimal
class OrderView(LoginRequiredMixin,View):


    def get(self,request):
        user = request.user

        #查询用户的收获地址
        try:
            addresses = Address.objects.filter(user=user, is_deleted=False)
        except Exception as e:
           addresses = None
        redis_con = get_redis_connection('carts')
        redis_cart = redis_con.hgetall('carts_%s' % user.id)
        redis_selected = redis_con.smembers('selected_%s' % user.id)

        new_cart_dict = {}
        for sku_id in redis_selected:
           new_cart_dict[int(sku_id)]=int(redis_cart[sku_id])
           # 获取被勾选商品的sku_id
        sku_ids = new_cart_dict.keys()
        skus = SKU.objects.filter(id__in = sku_ids)

        total_count = 0
        total_amount = Decimal(0.00)
        for sku in list(skus):
            sku.count = new_cart_dict[int(sku_id)]
            sku.amount = sku.price*sku.count
            total_count += sku.count
            total_amount += sku.amount

        #指定默认邮费

        freigh = Decimal(10.00)

        #构造上下文
        context= {
            'addresses':addresses,
            'skus':skus,
            'total_count':total_count,
            'total_amount': total_amount,
            'freight':freigh,
            'payment_amount':total_amount+freigh,

        }


        return render(request,'place_order.html',context)